import 'package:flutter/material.dart';

class MqttConfigDialog extends StatefulWidget {
  final String initialBroker;
  final Function(String) onSave;

  const MqttConfigDialog({
    super.key,
    required this.initialBroker,
    required this.onSave,
  });

  @override
  State<MqttConfigDialog> createState() => _MqttConfigDialogState();
}

class _MqttConfigDialogState extends State<MqttConfigDialog> {
  late final TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.initialBroker);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('设置 MQTT Broker'),
      content: TextField(
        controller: _controller,
        decoration: const InputDecoration(
          labelText: 'Broker 地址',
          hintText: '例如: broker.emqx.io:1883',
          border: OutlineInputBorder(),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: () {
            widget.onSave(_controller.text.trim());
            Navigator.of(context).pop();
          },
          child: const Text('保存并重连'),
        ),
      ],
    );
  }
}
